<template>
<uni-shadow-root class="partials-measureCard-index"><block v-if="measurementJson&&productData">
    
    <view class="measure_card" @touchmove.stop.prevent="true" v-if="showCount">
      <view class="countContainer"> 
         <view class="countContainer_top">
            <view class="countContainer_top_image">
              <image mode="aspectFill" :data-url="productData.productInfo.imagePath" :data-urls="productData.productInfo.imageListWatcher" @click="_watchBigImage" :src="productData.productInfo.imagePath"></image>
            </view>
            <view class="countContainer_top_product_info_container">
               <view class="font_1">{{productData.productInfo.name}}</view>
               <view class="font_aaa font_08">商品编号: {{productData.productInfo.orderNumber}}</view>
               <view class="price font_14" v-if="(productData.measures&&productData.measures.length == 0)||!productData.measures">
                 <text v-if="productData.productInfo.promotion>0&&bindway!='pintuanOne'">￥{{productData.productInfo.promotionPrice}}</text>
                 <text v-else>￥{{productData.productInfo.price}}</text>
               </view>
               <view class="price font_14 price_group" v-else>
                  <view class="pintuan" v-if="productData.productInfo.promotionBean&&productData.productInfo.promotionBean.pintuanStrategy&&(bindway=='pintuanMore'||bindway=='addPintuan')">
                    <text class="show_price" v-if="measurementJson.promotionPrice">￥{{measurementJson.promotionPrice}}</text>
                    <text class="loading_price" v-else>￥{{measurementJson.price}}</text>
                  </view>
                  <view class="noPintuan" v-else>￥{{measurementJson.price}}</view>
                  <text class="tagPrice_font" v-if="measurementJson.price<measurementJson.tagPrice">￥{{measurementJson.tagPrice}}</text>
                  <text style="color:#aaa;font-size:24rpx;margin-left:8rpx;" v-if="(productData.measures.length == 0||!productData.measures)&&productData.productInfo.stock<=10">(仅剩：{{productData.productInfo.stock}})</text>
                  <text style="color:#aaa;font-size:24rpx;margin-left:8rpx" v-if="(productData.measures.length != 0&&productData.measures)&&measurementJson.stock<=10">(仅剩：{{measurementJson.stock}})</text>
               </view>
               
            </view>
         </view>
        <view class="measureItemContainer">
            <view v-for="(types,index) in (productData.measures)" :key="types.id" class="cardMid">
              <view class="cardMidName">{{types.name}}</view>
              <radio-group class="cardMidGuigeContainer" :name="types.name" @change="chooseMeasure">
                <label v-for="(measures,i) in (types.productAssignMeasure)" :key="measures.i" class="font_08" :data-index="(index)+'-'+(i)" @click.stop.prevent="radioChange" :data-value="measures.measureName" :data-type="types.name">
                  <view :class="types.checkedMeasureItem == i? 'activeMeasure':''" :style="'background:'+(types.checkedMeasureItem == i? setting.platformSetting.defaultColor:'')+';color:'+(types.checkedMeasureItem == i? '#fff':setting.platformSetting.defaultColor)">{{measures.measureName}}</view>
                  <radio :checked="types.checkedMeasureItem == i" :value="(measures.measureTypeName)+'-'+(measures.id)" hidden="true"></radio>
                </label>
              </radio-group>
            </view>
          </view>
          <view class="error_view font_08" :style="'background:'+(setting.platformSetting.defaultColor)" v-if="measurementJson.stock < byNowParams.itemCount">
            <text>库存不足:(</text>
            <text v-for="(mtype,index) in (measurementJson.measurements)">-{{mtype.measureName}}</text>
            
            <text>)剩余库存【{{measurementJson.stock}}】</text>
          </view>
    
          <view class="ItemCountDell">
            <view class="font_777 font_09">购买数量</view>
              <view class="item_infomation_nums"> 
                <image style="border-top-left-radius: 0.2em;border-bottom-left-radius: 0.2em;" src="https://image1.sansancloud.com/xianhua/2019_12/17/21/40/33_565.jpg?x-oss-process=style/preview_120" :class="byNowParams.itemCount == minCount ?'noadd':''" @click.stop.prevent="subNum"></image>
                <text class="flexCenter">{{byNowParams.itemCount}}</text>
                <image style="border-top-right-radius: 0.2em; border-bottom-right-radius: 0.2em;" src="https://image1.sansancloud.com/xianhua/2019_12/17/21/40/33_660.jpg?x-oss-process=style/preview_120" :class="byNowParams.itemCount > measurementJson.stock?'noadd':''" :data-cantadd="(byNowParams.itemCount > measurementJson.stock?1:0)+' '" @click.stop.prevent="addNum"></image>
              </view>
          </view>
          <button v-if="bindway !== 'select'" :style="'background:'+(setting.platformSetting.defaultColor)" class="sureButn" :disabled="byNowParams.itemCount > measurementJson.stock||!measurementJson.waitDataState" @click="buyNow">确定</button>
          <view class="selectType" v-if="bindway == 'select'">
              <button :style="'background:'+(setting.platformSetting.defaultColor)" class="sureButnType" :disabled="byNowParams.itemCount > measurementJson.stock" data-way="cart" @click="buyNow">加入购物车</button>
              <button :style="'background:'+(setting.platformSetting.defaultColor)" class="sureButnType" :disabled="byNowParams.itemCount > measurementJson.stock" data-way="buy" @click="buyNow">立即购买</button>
          </view>
    
      </view>
    
      <view class="zhezhao" v-if="showCount" @click="closeZhezhao"></view>
    </view>
</block>


<view class="zhezhao" @click="closeFormZhezhao" v-if="showPerFormState"></view>
<view class="popupFormDetail" :animation="animationData">
 <view class="form_title">
   <text></text>
   <text>请填写以下信息</text>
   <image class="close_popup_icon" src="https://image1.sansancloud.com/xianhua/2019_7/31/15/25/40_755.jpg?x-oss-process=style/preview_120" @click="closeZhezhao"></image>
 </view>
 <scroll-view scroll-y style="max-height:700rpx">
   <view v-if="sendOptionData&&showPerFormState">
      <component-form-detail id="submitOrderForm" :receiveData="sendOptionData" :showTitle="false" :showBtn="false" @sendDataFun="getDataFun"></component-form-detail>
   </view>
   </scroll-view>
</view>
<view v-if="sendOptionData&&showPerFormState" class="submitBtn" :style="'background:'+(setting.platformSetting.defaultColor)" @click="submitData">
 <text>提交</text>
</view></uni-shadow-root>
</template>
<wxs src="../../public/publicFun.wxs" module="publicFun"></wxs>
<script>
import ComponentFormDetail from '../form_detail/index.vue'
global['__wxVueOptions'] = {components:{'component-form-detail': ComponentFormDetail}}

global['__wxRoute'] = 'partials/measureCard/index'
const app = getApp();
Component({
  properties: {
    showCount: {
      type: JSON,
    },
    productData: {
      type: JSON,
    },
    bindway: {
      type: JSON,
    },
    byNowParams:{
      type: JSON,
    },
    pintuanParams:{
      type: JSON,
    }
  },
  data: {
    someData: {},
    sysWidth:"",
    setting:null,
    measurementJson: null,
    MeasureParams:[],
    showPerFormState:false,
    animationData:null,
    sendOptionData:null,
  },
  ready:function(){
   let that=this;
   console.log("measureCard",that.data.showCount,that.data.byNowParams,that.data.productData)
   that.setData({
     setting: app.globalData.setting
   })
   if(that.data.productData){
      that.chooseMeasureItem()
   }
  },
  methods: {
      closeZhezhao: function () {
        let that=this;
        that.setData({ showCount: false })
        that.triggerEvent('closeCard', {state:'success'})
      },
      /* 立即购买 */
      buyNow: function (e) {
        let that=this;
        app.globalData.consoleFun("=====productList组件-buyNow=====",[e])
        if (!app.globalData.checkShopOpenTime()) {
          return
        }
        if (!app.globalData.checkIfLogin()) {
          return
        }
        let bindway;
        if (e.currentTarget.dataset.way) {
          bindway = e.currentTarget.dataset.way
        } else {
          bindway = that.data.bindway
        }
        app.globalData.consoleFun("=====productList组件-bindway=====",[bindway])
        that.setData({ haveMeasuresState: true })
        that.setData({ selectTypeData: that.data.selectTypeData })
        app.globalData.consoleFun("=====productList组件-addtocart=====")
        if(bindway=='cart'){
          that.addtocart()
        }else{
          that.createOrder22(that.data.byNowParams);
        }
      },
      /* 创建订单 */
      createOrder22: function (o,formId) {
        console.log('========createOrder22======', o);
        let that = this;
        let productInfo = that.data.productData.productInfo;
        if(!formId&&productInfo.preOrderCustomFormId){
            that.animationDataFun();
            return
        }
        let params = Object.assign({}, params, that.data.byNowParams, that.data.pintuanParams);
        console.log("=======", that.data.byNowParams, that.data.pintuanParams);
        app.globalData.showToastLoading('loading', true);
        app.globalData.createOrder(that.data.byNowParams, that.data.pintuanParams,formId||'');
      },
      animationDataFun:function(type){
          let that=this;
          let showPerFormState=!that.showPerFormState;
          let productInfo = that.data.productData.productInfo;
          that.setData({
            sendOptionData: !productInfo.preOrderCustomFormId?null:{ customFormId: productInfo.preOrderCustomFormId||0},
            showPerFormState: showPerFormState,
          })
          console.log("showPerFormState",showPerFormState,that.sendOptionData)
          let animation = wx.createAnimation({
            duration: 400,
            timingFunction: 'ease',
          })
          animation.bottom('100rpx').step()
          that.setData({
            animationData: animation.export(),
          })
      },
      submitData:function(){
          let that=this;
          that.selectComponent("#submitOrderForm").formSubmit();
      },
      getDataFun: function (e) {
        let that = this;
        console.log("===getDataFun===", e, e.detail.formId)
        // that.submitInvoiceFun(e.detail.formId)
        that.createOrder22(that.data.byNowParams,e.detail.formId)
      },
      closeFormZhezhao:function(){
        console.log("======closeZhezhao=========")
        let that=this;
        that.setData({ showPerFormState: false })
        let animation = wx.createAnimation({
          duration: 400,
          timingFunction: 'ease',
        })
        animation.bottom('-200rpx').step()
        let setData = animation.export()
        that.setData({
          animationData: setData,
        })
      },
      // 这里是一个自定义方法
      // readyAddCar: function (data) {
      //   let that = this;
      //   app.globalData.consoleFun("=====productList组件-readyAddCar=====",[ data, that.data.byNowParams])
      //   let productInfo =data.productInfo;
      //   let productId = productInfo.productId || productInfo.id
      //   app.globalData.consoleFun("=====productList组件-productId=====",[productId])
      //   that.get_product_measure(productId)
      // },
      //获取规格价格参数
      // get_product_measure: function (id) {
      //   let that=this;
      //   let productId = id
      //   let customIndex = app.globalData.AddClientUrl("/get_product_measures.html", { productId: productId})
      //   wx.request({
      //     url: customIndex.url,
      //     header: app.globalData.header,
      //     success: function (res) {
      //       app.globalData.consoleFun("=====productList组件-success=====",[res.data])
      //       let measures = res.data;
      //       that.data.productData.measures = measures
      //       that.setData({ productData: that.data.productData})
      //       if (measures.length == 0) {
      //         that.addtocart()
      //       } else {
      //         that.setData({ bindway: "cart", showCount: true })
      //         let info = that.data.productData.productInfo;
      //         app.globalData.consoleFun("=====productList组件-info=====",[info])
      //         that.data.byNowParams.productId = info.id
      //         that.data.byNowParams.shopId = info.belongShopId || info.shopId
      //         that.data.byNowParams.orderType = 0
      //         that.setData({ byNowParams: that.data.byNowParams })
      //         app.globalData.consoleFun("=====productList组件-byNowParams=====",[that.data.byNowParams])
      //         that.chooseMeasureItem()
      //       }
      //     },
      //     fail: function (res) {
      //       app.globalData.consoleFun("=====productList组件-fail=====")
      //       app.globalData.loadFail()
      //     },
      //     complete: function () {
      //     },
      //   })
      // },
      /* 初始化 选规格 */
      chooseMeasureItem: function (event) {
        app.globalData.consoleFun("=====productList组件-初始化规格参数=====",[event])
        let that=this;
        let productData = that.data.productData
        let focusProduct = productData
        let selectTypeData = []
        for (let i = 0; i < focusProduct.measures.length; i++) {
          focusProduct.measures[i].checkedMeasureItem = 0
          let param = {}
          let selectTypeDataItem = {}
          param.name = focusProduct.measures[i].name
          param.value = focusProduct.measures[i].productAssignMeasure[0].id
          selectTypeDataItem.type = focusProduct.measures[i].name
          selectTypeDataItem.value = focusProduct.measures[i].productAssignMeasure[0].measureName
          app.globalData.consoleFun("=====productList组件-param=====",[param])
          that.data.MeasureParams.push(param)
          selectTypeData.push(selectTypeDataItem)
        }
        that.data.selectTypeData = selectTypeData
        app.globalData.consoleFun("=====productList组件-selectTypeData=====",[that.data.selectTypeData])
        that.setData({
          productData: focusProduct
        })
        app.globalData.consoleFun("=====productList组件-MeasureParams=====",[that.data.MeasureParams])
        that.get_measure_cartesion()
      },
      //选择规格小巷的---显示
      radioChange: function (e) {
        let that = this
        let flag = false;
        app.globalData.consoleFun("=====productList组件-radioChange=====",[e])
        app.globalData.consoleFun("=====productList组件-selectTypeData=====",[that.data.selectTypeData])
        if (that.data.selectTypeData) {
          for (let i = 0; i < that.data.selectTypeData.length; i++) {
            if (e.currentTarget.dataset.type == that.data.selectTypeData[i].type) {
              that.data.selectTypeData.splice(i, 1, e.currentTarget.dataset)
              flag = true;
            }
          }
          if (!flag) {
            that.data.selectTypeData.splice(that.data.selectTypeData.length, 1, e.currentTarget.dataset)
            flag = false;
          }
        } else {
          that.data.selectTypeData = [];
          that.data.selectTypeData.splice(0, 1, e.currentTarget.dataset)
          that.setData({ selectTypeData: that.data.selectTypeData })
        }
        app.globalData.consoleFun("=====productList组件-selectTypeData=====",[that.data.selectTypeData])
        let index = e.currentTarget.dataset.index
        let indexJson = app.globalData.getSpaceStr(index, '-')
        let focusItem = that.data.productData
        focusItem.measures[indexJson.str1].checkedMeasureItem = indexJson.str2
        that.setData({ productData: focusItem })
      },
      //选择规格小巷---获取数据
      chooseMeasure: function (e) {
        app.globalData.consoleFun("=====productList组件-chooseMeasure=====",[e.detail.value])
        let chooseMeasureJson = app.globalData.getSpaceStr(e.detail.value, '-')
        app.globalData.consoleFun("=====productList组件-chooseMeasureJson=====",[chooseMeasureJson])
        for (let i = 0; i < this.data.MeasureParams.length; i++) {
          if (this.data.MeasureParams[i].name == chooseMeasureJson.str1) {
            this.data.MeasureParams[i].value = chooseMeasureJson.str2
          }
        }
        this.get_measure_cartesion()
      },
      //获取规格价格参数
      get_measure_cartesion: function () {
        let that = this
        that.setData({ measurementJson: { waitDataState: false } })
        let productId = that.data.productData.productInfo.productId||that.data.productData.productInfo.id
        let postStr = ''
        if (that.data.MeasureParams.length == 0) {
          that.data.byNowParams.cartesianId = '0'
          that.data.byNowParams.itemCount = that.data.productData.productInfo.minSaleCount
          that.setData({ minCount: that.data.byNowParams.itemCount,byNowParams: that.data.byNowParams, measurementJson: { waitDataState: true } })
          return
        }
        for (let i = 0; i < that.data.MeasureParams.length; i++) {
          postStr += that.data.MeasureParams[i].value + ','
        }
        let param = {}
        param.productId = productId
        param.measureIds = postStr
        app.globalData.consoleFun("=====productList组件-get_measure_cartesion=====",[postStr])
        let customIndex = app.globalData.AddClientUrl("/get_measure_cartesion.html", param)
        wx.request({
          url: customIndex.url,
          header: app.globalData.header,
          success: function (res) {
            app.globalData.consoleFun("=====productList组件-measurementJson=====",[res.data])
            that.data.byNowParams.cartesianId = res.data.id
            that.setData({
              measurementJson: res.data
            })
            that.data.measurementJson.waitDataState = true
            that.setData({ measurementJson: that.data.measurementJson })
            that.data.byNowParams.itemCount = that.data.measurementJson.minSaleCount
            that.setData({ minCount: that.data.byNowParams.itemCount})
            that.setData({ byNowParams: that.data.byNowParams })
          },
          fail: function (res) {
            app.globalData.consoleFun("=====productList组件-fail=====")
            app.globalData.loadFail()
          },
          complete: function () {
          },
        })
      },
      subNum: function () {
        let that=this;
        console.log("this.data.measurementJson",that.data.measurementJson)
        if (that.data.measurementJson&&that.data.measurementJson.id) {
          that.setData({ minCount: that.data.measurementJson.minSaleCount })
        } else {
          that.setData({ minCount: 1 })
        }
        if (that.data.byNowParams.itemCount == that.data.minCount) {
          return
        }
        that.data.byNowParams.itemCount--;
        that.setData({ byNowParams: that.data.byNowParams })
      },
      addNum: function () {
        this.data.byNowParams.itemCount++;
        this.setData({ byNowParams: this.data.byNowParams })
      },
      addtocart: function () {
        app.globalData.consoleFun("=====productList组件-addtocart=====")
        if (!app.globalData.checkIfLogin()) {
          return
        }
        var params = {
          cartesianId: '',
          productId: '',
          shopId: '',
          count: '',
          type: '',
        }
        if (this.data.productData.measures.length == 0) {
          params.cartesianId = '0'
        }
        else {
          params.cartesianId = this.data.measurementJson.id
        }
        let productId = this.data.productData.productInfo.productId || this.data.productData.productInfo.id
        app.globalData.consoleFun("=====productList组件-productId=====",[productId])
        params.productId = productId
        params.shopId = this.data.productData.productInfo.belongShopId || this.data.productData.productInfo.shopId
        params.count = this.data.byNowParams.itemCount
        params.type = 'add'
        app.globalData.consoleFun("=====productList组件-params=====",[params])
        this.postParams(params)
      },
      postParams: function (data) {
        app.globalData.consoleFun("=====productList组件-postParams=====")
        var that = this
        var customIndex = app.globalData.AddClientUrl("/change_shopping_car_item.html", data, 'post')
        wx.request({
          url: customIndex.url,
          data: customIndex.params,
          header: app.globalData.headerPost,
          method: 'POST',
          success: function (res) {
            let resEventData = res.data
            that.triggerEvent('resEvent', { resEventData}, {})
            app.globalData.consoleFun("=====productList组件-change_shopping_car_item=====",[res.data])
            wx.hideLoading()
            if (that.data.bindway == 'cart') {
              that.setData({ showCount: false })
            }
            if (data.productId == 0) {
              app.globalData.consoleFun("=====productList组件-购物车里面的商品数量=====")
              that.setData({
                countGood: res.data.totalCarItemCount
              })
            } else {
              if (res.data.productId && res.data.productId != 0) {
                if (data.count == 0) {
                  app.globalData.consoleFun("=====productList组件-通过加入购物车来确定购物车里面的商品数量=====")
                } else {
                  wx.showToast({
                    title: '加入购物车成功',
                  })
                }
                if (!!res.data.totalCarItemCount || res.data.totalCarItemCount == 0) {
                  that.setData({ countGood: res.data.totalCarItemCount })
                }
              } else {
                wx.showToast({
                  title: res.data.errMsg,
                  image: '/wxcomponents/images/icons/tip.png',
                  duration: 2000
                })
              }
            }
            try {
              app.globalData.carChangeNotify(res.data);
            } catch (e) { }
            app.globalData.consoleFun("=====productList组件-加入购物车动作=====")
            that.triggerEvent('closeCard', {state:'success'})
          },
          fail: function (res) {
            wx.hideLoading()
            app.globalData.loadFail()
          }
        })
      },
      //提交规格产品
      submitMeasure: function (id) {
        var that = this
        let focusProduct = this.data.MeasureItem
        let measurementJson = this.data.measurementJson
        let data = {}
        data.cartesianId = measurementJson.id
        data.productId = focusProduct.id
        data.shopId = focusProduct.belongShopId
        data.count = 1
        data.type = 'add'
        var customIndex = app.globalData.AddClientUrl("/change_shopping_car_item.html", data, 'post')
        wx.request({
          url: customIndex.url,
          data: customIndex.params,
          header: app.globalData.headerPost,
          method: 'POST',
          success: function (res) {
            app.globalData.consoleFun("=====productList组件-add=====",[res.data])
            that.setData({ showGuigeType: false })
          },
          fail: function (res) {
            app.globalData.loadFail()
          },
          complete: function () {
            wx.hideLoading()
          }
        })
      },
      closeGuigeZhezhao: function () {
        this.setData({ showGuigeType: false })
        this.data.MeasureParams = []
      },
      tolinkUrl: function (e) {
        app.globalData.consoleFun("=====productList组件-tolinkUrl=====",[e.currentTarget.dataset.info])
        let productData = e.currentTarget.dataset.info
        let link="";
        if (productData.productType==6){
          link = "ticket_detail.html?productId=" + productData.id; 
        }else{
          link = "product_detail.html?productId=" + productData.id; 
        }
        app.globalData.linkEvent(link);
      }
  },
})
export default global['__wxComponents']['partials/measureCard/index']
</script>
<style platform="mp-weixin">
@import 'measure_card/measure_card.css';

/* 提交报名 */
.popupFormDetail{
  max-height: 950rpx;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: fixed;
  bottom: -200rpx;
  z-index:13;
  background:#fff;
  box-sizing:border-box;
}
.form_title{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  border-bottom:1rpx solid #eee;
  font-size:30rpx;
  padding:20rpx;
}
.close_popup_icon{
  width: 40rpx;
  height: 40rpx;
}
.submitBtn{
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  bottom:0;
  width: 100%;
  color: #fff;
  padding: 20rpx;
  z-index: 13;
  box-sizing:border-box;
  background: #fff;
  height: 100rpx;
  font-size: 30rpx;
}
</style>